<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/25
 * Time: 14:42
 */
namespace app\shop\controller;
use app\admin\model\Node;
use app\admin\model\UserType;
use think\Db;
class Index extends Base
{
    public function index(){
        extract(input());
        $search = input('param.search/a');
        $page = input('param.page');
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }

        $search = $this->search($search, $page);
        //搜索条件
        $map = [];
        //任务名称
        if($search[0] != ""){
            $map['uy_name'] = ['like',"%" . $search[0] . "%"];
        }else{
            $map['uy_fid'] = 0;
        }
        $map['uy_user_id'] = session('user_id');
        $map['uy_status'] = 1;
        $data = Db::table('up_user_yun')
            ->where($map)
            ->order('uy_type asc,uy_time desc')
            ->paginate(10);
        $this->assign([
            'data' => $data,
            'pages'=>$pages,
            'uy_id'=>'',
            'search'=>$search
        ]);
        return $this->fetch ();
    }
    public function indexInfo(){
        extract(input());
        $search = input('param.search/a');
        $page = input('param.page');
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }
        $search = $this->search($search, $page);
        //搜索条件
        $map = [];
        //任务名称
        if($search[0] != ""){
            $map['uy_name'] = ['like',"%" . $search[0] . "%"];
        }
        if(isset($uy_id) && $uy_id){
            $map['uy_fid'] = $uy_id;
            session('uy_id_fid',$uy_id);
        }else{
            $map['uy_fid'] = session('uy_id_fid');
        }
        $map['uy_user_id'] = session('user_id');
        $map['uy_status'] = 1;
        $data = Db::table('up_user_yun')
            ->where($map)
            ->order('uy_type asc,uy_time desc')
            ->paginate(10);
        $this->assign([
            'data' => $data,
            'pages'=>$pages,
            'uy_id'=>$map['uy_fid'],
            'search'=>$search
        ]);
        return $this->fetch ('index/index');
    }
    /**
     * [giveAccess 分配目录]
     * @return [type] [description]
     * @author
     */
    public function giveAccess()
    {
        $param = input('param.');
        $node = new Node();
        //获取现在的权限
        if('get' == $param['type']){
            $where = [];
            $where['uy_user_id'] = session('user_id');
            $where['uy_status'] = 1;
            $where['uy_type'] = 1;
            $result = Db::table('up_user_yun')
                ->field('uy_id,uy_name,uy_fid')
                ->where($where)
                ->select();
            $str = "";
            foreach($result as $key=>$vo){
                //加个isParent:true，没有子节点时也显示文件夹
                $str .= '{ "id": "' . $vo['uy_id'] . '", "pId":"' . $vo['uy_fid'] . '", "name":"' . $vo['uy_name'].'","isParent":true';
                $str .= '},';
            }

            $resultdata = "[" . substr($str, 0, -1) . "]";
            return json(['code' => 200, 'data' => $resultdata, 'msg' => 'success']);
        }
    }
    /**
     * 复制或移动
     * 从聊天处保存到自己的网盘传复制类型即可
     * type：1复制  2移动
     * fid：目标id
     * @return \think\response\Json
     */
    public function fileCopyMove()
    {
        extract(input());
        $user_id = session('user_id');
        if($fid > 0 && $fid) {
            $fstatus = Db::table('up_user_yun')->where('uy_id', $fid)->value('uy_status');
            if ($fstatus != 1) {
                return json(['code' => 100, 'msg' => '目标文件夹不存在，请重新选择']);
            }
        }
        //--------------------不能复制或移动到自身或子目录下 start -------------------------
        $no_1 = Db::table('up_user_yun')
            ->where('uy_id', 'in',$ids)
            ->where('uy_type', 1)
            ->field('uy_id_str')
            ->select();
        if($no_1){
            $no_2 = Db::table('up_user_yun')->where('uy_id',$fid)->value('uy_id_str');
            foreach ($no_1 as $nok => $nov){
                if(strstr($no_2,$nov['uy_id_str'])){
                    return json(['status'=>0,'msg'=>'不能复制或移动到自身或子目录下']);
                }
            }
        }
        //--------------------不能复制或移动到自身或子目录下 end ------------------------
        $ids = explode(',',trim($ids,','));
        $user = $this->getUserInfo($user_id,'user_ram,user_ram_use',2);
        $can = $user['user_ram'] - $user['user_ram_use'];
        $allsize = 0;
        //----------------------------------------------------------------
        if($type == 1) {
            foreach ($ids as $kk => $vv) {
                //先判断复制的情况下内存够不够
                $uy_id = $vv;
                $self = Db::table('up_user_yun')->where('uy_id', $uy_id)->find();
                if ($self['uy_type'] == 1) {
                    $size = Db::table('up_user_yun')
                        ->where('uy_status', 1)
                        ->where('uy_id_str', 'like', '%' . $self['uy_id_str'] . '%')
                        ->sum('uy_size');
                } else {
                    $size = $self['uy_size'];
                }
                $allsize += $size;
            }
            if($can < $allsize){
                return json(['code'=>100,'msg'=>'内存不足']);
            }
            if($allsize > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_ram_use',$allsize);
            }
        }
        //----------------------------------------------------------------
        foreach ($ids as $kk => $vv){
            //先判断复制的情况下内存够不够
            $uy_id = $vv;
            $self = Db::table('up_user_yun')->where('uy_id',$uy_id)->find();
            //开始复制移动
            $self['uy_fid'] = $fid;
            $self['uy_user_id'] = $user_id;
            unset($self['uy_id']);
            //先插入拿到id，再改掉复制的这个文件的idstr
            $newid = Db::table('up_user_yun')->insertGetId($self);
            if($fid > 0 && $fid){
                $fstr = Db::table('up_user_yun')->where('uy_id',$fid)->value('uy_id_str');
                $id_str = $fstr . $newid . ',';
            }else{
                $id_str = ',' . $newid . ',';
            }
            Db::table('up_user_yun')->where('uy_id',$newid)->setField('uy_id_str',$id_str);
            if($self['uy_type'] == 1){
                $this->digui($uy_id,$newid,$user_id);
            }
            if($type == 2){
                Db::table('up_user_yun')
                    ->where('uy_status',1)
                    ->where('uy_id_str','like','%'.$self['uy_id_str'].'%')
                    ->delete();
            }
        }
        return json(['code'=>200,'msg'=>'操作成功']);
    }
    public function digui($uy_id,$newid,$user_id) //源文件夹id，目标文件夹id
    {
        //用fid的方式查，如果这个文件夹被冻结了，则此文件夹下的所有内容都不会被查出来，自带矫正
        //但是上面的用的是like的方式，会把下面的查出来，所以加了个status为3的情况，这样可以防止计算错误，在删除时别忘了3的情况
        //删除的时候不考虑特殊性，全删
        $self = Db::table('up_user_yun')
            ->where('uy_status',1)
            ->where('uy_fid',$uy_id)
            ->select();
        if($self){
            foreach ($self as $k => $v){
                //开始复制
                $oid = $v['uy_id'];
                $v['uy_fid'] = $newid;
                $v['uy_user_id'] = $user_id;
                unset($v['uy_id']);
                //先插入拿到id，再改掉复制的这个文件的idstr
                $newid2 = Db::table('up_user_yun')->insertGetId($v);
                $fstr = Db::table('up_user_yun')->where('uy_id',$newid)->value('uy_id_str');
                $id_str = $fstr . $newid2 . ',';
                Db::table('up_user_yun')->where('uy_id',$newid2)->setField('uy_id_str',$id_str);
                if($v['uy_type'] == 1){
                    $this->digui($oid,$newid2,$user_id);
                }
            }
        }
        return true;
    }
    /**
     * 重命名
     * @return \think\response\Json
     */
    public function updateName()
    {
        extract(input());
        $update = [
            'uy_name' => $name,
            'uy_update' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_user_yun')
            ->where('uy_id',$id)
            ->update($update);
        if($res){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败，请刷新重试']);
        }

    }
    /**
     * 加入回收站
     * @return \think\response\Json
     */
    public function delFake()
    {
        extract(input());
        Db::startTrans();
        try {
            $ids = trim($id,',');
            Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->setField('uy_status',2);
            $data = Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->select();
            foreach ($data as $k => $v){
                $have = Db::table('up_user_yun')
                    ->where('uy_status',1)
                    ->where('uy_id','<>',$v['uy_id'])
                    ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                    ->find();
                if($have){
                    Db::table('up_user_yun')
                        ->where('uy_status',1)
                        ->where('uy_id','<>',$v['uy_id'])
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->setField('uy_status',3);
                }
            }
            Db::commit();
            return json(['code'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'操作失败，请刷新测试']);
        }
    }
    /**
     * 新建文件夹
     */
    public function addFileTop()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        if(!$id){
            $id = 0;
        }
        $add = [
            'uy_user_id' => session('user_id'),
            'uy_fid' => $id,
            'uy_type' => 1,
            'uy_name' => $name,
            'uy_url' => '', //文件夹类型为空
            'uy_size' => 0,//文件夹类型为0
            'uy_time' => $today,
            'uy_update' => $today
        ];
        Db::startTrans();
        try {
            $id = Db::table('up_user_yun')->insertGetId($add);
            $id_str = ','.$id.',';
            Db::table('up_user_yun')->where('uy_id',$id)->setField('uy_id_str',$id_str);
            Db::commit();
            return json(['code'=>200,'msg'=>'新建成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'新建失败，请刷新测试']);
        }
    }
    /**
     * 新建
     */
    public function addFile()
    {
        extract(input());
        $user_id = session('user_id');
        $today = date('Y-m-d H:i:s');
        $user = $this->getUserInfo($user_id,'user_ram,user_ram_use',2);
        $can = $user['user_ram'] - $user['user_ram_use'];
        $name = explode('?size=',$name);
        $size = round($name[1]/1024,2);
        if($can < $size){
            return json(['code'=>0,'msg'=>'内存不足']);
        }
        if(!$id){
            $id = 0;
        }
        $add = [
            'uy_user_id' => $user_id,
            'uy_fid' => $id,
            'uy_type' => $type,
            'uy_name' => $oldname,
            'uy_url' => $name[0], //文件夹类型为空
            'uy_size' => $size,//文件夹类型为0
            'uy_time' => $today,
            'uy_update' => $today,
        ];
        Db::startTrans();
        try {
            $newid = Db::table('up_user_yun')->insertGetId($add);
            if($id == 0 || !$id){
                $id_str = ','.$newid.',';
            }else{
                $fstr = Db::table('up_user_yun')->where('uy_id',$id)->value('uy_id_str');
                $id_str = $fstr . $newid . ',';
            }
            Db::table('up_user_yun')->where('uy_id',$newid)->setField('uy_id_str',$id_str);
            if($size > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_ram_use',$size);
            }
            Db::commit();
            return json(['code'=>200,'msg'=>'上传成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'上传失败，请刷新测试']);
        }
    }
    /**
     * 单个下载
     */
    public function downloadOne()
    {
        $file_name = input('file_name');
        $mime = 'application/force-download';
        header('Pragma: public'); // required
        header('Expires: 0'); // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
        header('Content-Transfer-Encoding: binary');
        header('Connection: close');
        readfile($file_name); // push it out
        exit();
    }
    /**
     * 批量下载
     */
    public function downloadLot()
    {
        extract(input());
        $id = trim($id,',');
        $data = Db::table('up_user_yun')
            ->where('uy_id','in',$id)
            ->field('uy_type,uy_url,uy_name,uy_id_str')
            ->select();
        if($data){
            $pathname = 'img_'.session('user_id').time().rand(10000,99999);
            $img_path = ROOT_PATH . 'public' . DS . 'uploads/img/'.$pathname;
            if (!file_exists($img_path)) {
                mkdir($img_path);
            }
            $res = [];
            foreach ($data as $k => $v){
                if($v['uy_type'] != 1){
                    $res[] = $v;
                }else{
                    $son = Db::table('up_user_yun')
                        ->where('uy_id_str','like',"%{$v['uy_id_str']}%")
                        ->where('uy_status',1)
                        ->where('uy_type','>',1)
                        ->field('uy_type,uy_url,uy_name,uy_id_str')
                        ->select();
                    $res = array_merge($res,$son);
                }
            }
            if($res){
                $mww_upload =  new \app\shop\controller\Upload();
                //下载图片
                foreach ($res as $k2 => $v2){
                    $mww_upload->mulu($v2,$img_path);
                }
                $mww_upload->xiazaiFf($pathname,$img_path);
            }
        }
    }
}